package com.edais.actions;

import java.io.Serializable;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.alibaba.fastjson.JSONObject;
import com.edais.domain.Scattered;
import com.edais.domain.UserChannelPoint;
import com.edais.service.LoanService;
import com.edais.service.UserChannelPointService;
import com.edais.util.CommonUtil;
import com.edais.util.Consts;
import com.edais.util.DecimalFormatUtil;
import com.edais.util.Message;
import com.lb.sssq.service.DepositService;

/** 标的action */
@Controller
@RequestMapping("/loan")

public class LoanAction  implements Serializable{
	/** 日志 */
	private static final Log logger = LogFactory.getLog(LoanAction.class);

	/** 设置service */
	@Autowired
	private LoanService loanService;
	
	@Autowired
	UserChannelPointService userChannelPointService;
	
	@Autowired
	private DepositService depositService;

	/**
	 * 获取标的基本信息列表
	 * 
	 * @param request
	 * @return response
	 * @throws Exception
	 */
	@RequestMapping(value = "/getLoanBaseInfoList")
	public void getLoanBaseInfoList(HttpServletRequest request,
			HttpServletResponse response) {
		Map<String, Object> jsonMap = new HashMap<String, Object>();

		// 解密请求参数
		Map<String, String> paramsMap = CommonUtil.decryptParamters(request);
//		String categoryId = paramsMap.get("categoryId");// 标的大分类ID
		String sort = paramsMap.get("sort");// 排序 1:年化收益率 2:借款期限
		String currentPageStr = paramsMap.get(Consts.Page.PAGE_CURRENT_NAME);//当前页
		String pageSizeStr = paramsMap.get(Consts.Page.PAGE_SIZE_NAME);//页大小
		Integer current = 1;
		Integer pageSize = 10;//默认显示10条

		try {
			// 参数检查
			Map<String, String> checkRes = getLoanListCheck(paramsMap);
			if (!Consts.SUCCESS_CODE.equals(checkRes.get("code"))) {
				logger.error("获取标的列表信息数据检查失败:" + checkRes.get("message"));
				String result = CommonUtil.setResultStringCn(
						new HashMap<String, Object>(), checkRes.get("code"),
						"", checkRes.get("message"));
				CommonUtil.responseJson(result, response);
				return;
			}
			
			//分页参数
			if (currentPageStr != null && !("".equals(currentPageStr))) {
				current = Integer.parseInt(currentPageStr);
			}
			if (pageSizeStr != null && !("".equals(pageSizeStr))) {
				pageSize = Integer.parseInt(pageSizeStr);
			}
			
			// 获取标的列表信息
			HashMap<String,Object> map = new HashMap<String,Object>();
			map.put("rowBegin", (current-1) * pageSize);
			map.put("rowEnd", pageSize);
			map.put("bidingWay", 2);
//			map.put("categoryId", categoryId);
			map.put("sort", paramsMap.get("sort"));
			
			String result = loanService.getLoanBaseInfoList(map);
			
			// 处理返回结果
			CommonUtil.responseJson(result, response);
		} catch (Exception e) {
			logger.error("loan/getLoanBaseInfoList 异常:" + e.getMessage());
			String result = CommonUtil.setResultStringCn(
				new HashMap<String, Object>(),Consts.ERROR_CODE, "",e.getMessage());
			// 处理返回结果
			CommonUtil.responseJson(result, response);
			return;
		}
	}
	
	private Map<String,String> getLoanListCheck(Map<String,String> map){
		Map<String,String> resultMap = new HashMap<String,String>();
//		String categoryId = map.get("categoryId");// 标的大分类ID
		String sort = map.get("sort");// 排序 1:年化收益率 2:借款期限
		
		/*if(StringUtils.isBlank(categoryId)){
			resultMap.put("code", Consts.ERROR_CODE);
			resultMap.put("message",
					Message.CnDescriptionExpression.BUSINESSE_ERROR);
			return resultMap;
		}*/
		
		if(!("1".equals(sort) || "2".equals(sort)) || StringUtils.isBlank(sort)){
			map.put("sort", "1");
		}
		
		resultMap.put("code", Consts.SUCCESS_CODE);
		resultMap.put("message", Consts.SUCCESS_DESCRIBE);
		
		return resultMap;
	}
	
	
	
	/**
	 * 散标投资人列表(微信)定期
	 * 
	 * @param request
	 * @return response
	 * @throws Exception
	 */
	@RequestMapping(value = "/getUserListByLoanIdForWx")
	public void getUserListByLoanIdForWx(HttpServletRequest request,
			HttpServletResponse response) {
		// 解密请求参数
		Map<String, String> paramsMap = CommonUtil.decryptParamters(request);
//		String loanId = paramsMap.get("scatteredLoanId");// 标的id(key)
		String scatteredLoanId = paramsMap.get("scatteredLoanId");// 标的id(key)
		String currentPageStr = paramsMap.get(Consts.Page.PAGE_CURRENT_NAME);//当前页
		String pageSizeStr = paramsMap.get(Consts.Page.PAGE_SIZE_NAME);//页大小
		Integer current = 1;
		Integer pageSize = 10;//默认显示10条

		try {
			// 参数检查
			Map<String, String> checkRes = getUserListByLoanIdWxCheck(paramsMap);
			if (!Consts.SUCCESS_CODE.equals(checkRes.get("code"))) {
				logger.error("获取散标投资人列表数据检查失败:" + checkRes.get("message"));
				String result = CommonUtil.setResultStringCn(
						new HashMap<String, Object>(), checkRes.get("code"),
						"", checkRes.get("message"));
				CommonUtil.responseJson(result, response);
				return;
			}
			
			//分页参数
			if (currentPageStr != null && !("".equals(currentPageStr))) {
				current = Integer.parseInt(currentPageStr);
			}
			if (pageSizeStr != null && !("".equals(pageSizeStr))) {
				pageSize = Integer.parseInt(pageSizeStr);
			}
			
			// 获取标的列表信息
			HashMap<String,Object> map = new HashMap<String,Object>();
//			map.put("scatteredLoanId",loanId);
			map.put("scatteredLoanId",scatteredLoanId);
			map.put("currentPage", current);
			map.put("pageSize", pageSize);
			
			String result = loanService.getUserListByLoanIdForWx(map);
			
			// 处理返回结果
			CommonUtil.responseJson(result, response);
		} catch (Exception e) {
			logger.error("loan/getLoanDetailInfo 异常:" + e.getMessage());
			String result = CommonUtil.setResultStringCn(
				new HashMap<String, Object>(),Consts.ERROR_CODE, "",e.getMessage());
			// 处理返回结果
			CommonUtil.responseJson(result, response);
			return;
		}
	}
	
	
	
	/**
	 * 散标投资人列表（app）活期
	 * 
	 * @param request
	 * @return response
	 * @throws Exception
	 */
	@RequestMapping(value = "/getUserListByLoanId")
	public void getUserListByLoanId(HttpServletRequest request,
			HttpServletResponse response) {
		// 解密请求参数
		Map<String, String> paramsMap = CommonUtil.decryptParamters(request);
//		String loanId = paramsMap.get("scatteredLoanId");// 标的id(key)
		String loanId = paramsMap.get("loanId");// 标的id(key)
		String currentPageStr = paramsMap.get(Consts.Page.PAGE_CURRENT_NAME);//当前页
		String pageSizeStr = paramsMap.get(Consts.Page.PAGE_SIZE_NAME);//页大小
		Integer current = 1;
		Integer pageSize = 10;//默认显示10条

		try {
			// 参数检查
			Map<String, String> checkRes = getUserListByLoanIdCheck(paramsMap);
			if (!Consts.SUCCESS_CODE.equals(checkRes.get("code"))) {
				logger.error("获取散标投资人列表数据检查失败:" + checkRes.get("message"));
				String result = CommonUtil.setResultStringCn(
						new HashMap<String, Object>(), checkRes.get("code"),
						"", checkRes.get("message"));
				CommonUtil.responseJson(result, response);
				return;
			}
			
			//分页参数
			if (currentPageStr != null && !("".equals(currentPageStr))) {
				current = Integer.parseInt(currentPageStr);
			}
			if (pageSizeStr != null && !("".equals(pageSizeStr))) {
				pageSize = Integer.parseInt(pageSizeStr);
			}
			
			// 获取标的列表信息
			HashMap<String,Object> map = new HashMap<String,Object>();
//			map.put("scatteredLoanId",loanId);
			map.put("loanId",loanId);
			map.put("currentPage", current);
			map.put("pageSize", pageSize);
			
			String result = loanService.getUserListByLoanId(map);
			
			// 处理返回结果
			CommonUtil.responseJson(result, response);
		} catch (Exception e) {
			logger.error("loan/getLoanDetailInfo 异常:" + e.getMessage());
			String result = CommonUtil.setResultStringCn(
				new HashMap<String, Object>(),Consts.ERROR_CODE, "",e.getMessage());
			// 处理返回结果
			CommonUtil.responseJson(result, response);
			return;
		}
	}
	

	
	private Map<String,String> getLoanDetailCheck(Map<String,String> map){
		Map<String,String> resultMap = new HashMap<String,String>();
		String loanId = map.get("scatteredLoanId");// 标的id
		
		if(StringUtils.isBlank(loanId)){
			resultMap.put("code", Consts.ERROR_CODE);
			resultMap.put("message",
					Message.CnDescriptionExpression.BUSINESSE_ERROR);
			return resultMap;
		}
		
		resultMap.put("code", Consts.SUCCESS_CODE);
		resultMap.put("message", Consts.SUCCESS_DESCRIBE);
		
		return resultMap;
	}
	

	
	/**
	 * 散标列表
	 * 
	 * @param request
	 * @return response
	 * @throws Exception
	 */
	@RequestMapping(value = "/getLoanList")
	public void getLoanList(HttpServletRequest request,
			HttpServletResponse response) {
		long a=System.currentTimeMillis();
		Integer current = 1;
		Integer pageSize = 10;//默认显示10条
		
		// 解密请求参数
		Map<String, String> paramsMap = CommonUtil.decryptParamters(request);
		String currentPageStr = paramsMap.get(Consts.Page.PAGE_CURRENT_NAME);//当前页
		String pageSizeStr = paramsMap.get(Consts.Page.PAGE_SIZE_NAME);//页大小
		String userId = paramsMap.get("userId");
		String planId = paramsMap.get("planId");//页大小
		String sellingType = paramsMap.get("sellingType");//上架类别
		
		try{
			//分页参数
			if (currentPageStr != null && !("".equals(currentPageStr))) {
				current = Integer.parseInt(currentPageStr);
			}
			if (pageSizeStr != null && !("".equals(pageSizeStr))) {
				pageSize = Integer.parseInt(pageSizeStr);
			}
			
			Map<String,Object> map = new HashMap<String,Object>();
//			map.put("rowBegin",(current-1)*pageSize);
//			map.put("rowEnd",current*pageSize);
			map.put("rowBegin",(current-1)*pageSize);
			map.put("rowEnd",pageSize);
			map.put("planId",planId);
			map.put("sellingType",sellingType);
			map.put("startSellingTime",CommonUtil.getDateYYYYMMDDHH24MM());
			//获取上架产品总数
			String totalNum = loanService.queryScatteredLoanCount(map);
			List<Scattered> scatteredList = loanService.queryScatteredLoan(map);
			/**
			 * 剩余金额小于起头金额，返回100%
			 * 当产品已经超过下架时间，返回100%
			 */
			List<Map<String,Object>> resultListMap = new ArrayList<Map<String,Object>>();
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			
			Map<String, Object> map2 = new HashMap<String, Object>();
			String investUserNum = "";
			
			StringBuffer loadIdBf=new StringBuffer();
			for(int i =0;i<scatteredList.size();i++){
				loadIdBf.append(String.valueOf(scatteredList.get(i).getId())+",");
			}
			String loadId=loadIdBf.toString();
			Map<String,Object> listEx=null;
			
			if(loadId.lastIndexOf(",")!=-1){
				loadId=loadId.substring(0,loadId.lastIndexOf(","));
				logger.debug("queryOrderByIdPeopleNumEx传值参数-------"+loadId);
				map2.put("loanId", loadId);
				listEx=loanService.queryOrderByIdPeopleNumEx(map2);
				logger.debug("queryOrderByIdPeopleNumEx返回结果-------"+listEx);
			}
			
			//获取用户渠道等级积分数据
			UserChannelPoint userChannelPoint = null;
			if (StringUtils.isNotBlank(userId)) {
				Map<String,Object> parm = new HashMap<String, Object>();
				parm.put("userId", userId);
				userChannelPoint = userChannelPointService.findChannelPointByParm(parm);
			}

			for(int i =0;i<scatteredList.size();i++){
				Scattered sc = scatteredList.get(i);
				Map<String,Object> scMap = new HashMap<String,Object>();
				scMap.put("scatteredLoanId", sc.getId());//id
				scMap.put("productName", sc.getProductName());//
				scMap.put("borrowType", sc.getBorrowType());
				scMap.put("annualRate", sc.getAnnualRate());
				scMap.put("remanPeriods", sc.getRemanPeriods());
				scMap.put("remanDays", sc.getRemanDays());
				scMap.put("contactAmount", sc.getContactAmount());
//				scMap.put("finishedRatio", DecimalFormatUtil.getDecimalFormat0(sc.getFinishedRatio()));
//				scMap.put("finishedRatio", sc.getFinishedRatio());
				scMap.put("finishedRatio", DecimalFormatUtil.getDecimalFormat0(BigDecimal.ONE.compareTo(sc.getFinishedRatio())>0 && BigDecimal.ZERO.compareTo(sc.getFinishedRatio())<0?BigDecimal.ONE:sc.getFinishedRatio()));
				scMap.put("remanAmount", sc.getRemanAmount());
				scMap.put("perServingAmount", sc.getPerServingAmount());
				scMap.put("investMinAmount", sc.getInvestMinAmount());
				scMap.put("openSelling", sc.getOpenSelling());
				scMap.put("loanId", sc.getBidId());
				scMap.put("planId", sc.getPlanId());
				scMap.put("isAdjustRate", sc.getIsAdjustRate());
				
				BigDecimal adjustRate = BigDecimal.ZERO; 
				if ("Y".equals(sc.getIsAdjustRate())) {
					if (userChannelPoint != null) {
						adjustRate = sc.getMaxAdjustRate().multiply(
								new BigDecimal(userChannelPoint.getFixFloatRateChannel()));
					}
				}
				//调整利率
				scMap.put("adjustRate", adjustRate.setScale(1, RoundingMode.DOWN));

				// 获取标的列表人数
				if(listEx!=null&&listEx.size()!=0&&listEx.size()==scatteredList.size()){
					if(listEx.containsKey(String.valueOf(sc.getId()))){
						scMap.put("investUserNum", listEx.get(String.valueOf(sc.getId())));
					}else{
						scMap.put("investUserNum", "1");
					}
				}else{
					map2.put("loanId", sc.getId());
					investUserNum = loanService.queryOrderByIdPeopleNum(map2);
					scMap.put("investUserNum", investUserNum);
				}
				resultListMap.add(scMap);
			}
			
			Map<String, Object> mapResult = new HashMap<String, Object>();
			mapResult.put("totalNum", totalNum);
			mapResult.put("listSize", String.valueOf(resultListMap.size()));
			mapResult.put("list", resultListMap);
			
			mapResult.put("resmsg_cn", "");
			String result = CommonUtil.setResultInfo(mapResult, Consts.SUCCESS_CODE, Consts.SUCCESS_DESCRIBE);
			// 处理返回结果
			CommonUtil.responseJson(result, response);
			
		} catch (Exception e) {
			logger.error("获取散标列表数据发生异常:" + e.getMessage());
			String result = CommonUtil.setResultStringCn(
				new HashMap<String, Object>(),Consts.ERROR_CODE, "",e.getMessage());
			// 处理返回结果
			CommonUtil.responseJson(result, response);
			return;
		}finally{
			System.out.println("loan/getLoanList接口\t执行耗时："+(System.currentTimeMillis()-a)/1000f+"秒");
			logger.debug("loan/getLoanList接口\t执行耗时："+(System.currentTimeMillis()-a)/1000f+"秒");
		}
	}
	
	
	/**
	 * 散标列表(扩展条件:)
	 * 
	 * @param request
	 * @return response
	 * @throws Exception
	 */
	@RequestMapping(value = "/getLoanListInfo")
	public void getRegularLoanList(HttpServletRequest request,
			HttpServletResponse response) {
		long a=System.currentTimeMillis();
		Integer current = 1;
		Integer pageSize = 10;//默认显示10条
		
		// 解密请求参数
		Map<String, String> paramsMap = CommonUtil.decryptParamters(request);
		String currentPageStr = paramsMap.get(Consts.Page.PAGE_CURRENT_NAME);//当前页
		String pageSizeStr = paramsMap.get(Consts.Page.PAGE_SIZE_NAME);//页大小
		String userId = paramsMap.get("userId");
		String planId = paramsMap.get("planId");//页大小
		String sellingType = paramsMap.get("sellingType");//上架类别
		
		try{
			//分页参数
			if (currentPageStr != null && !("".equals(currentPageStr))) {
				current = Integer.parseInt(currentPageStr);
			}
			if (pageSizeStr != null && !("".equals(pageSizeStr))) {
				pageSize = Integer.parseInt(pageSizeStr);
			}
			
			Map<String,Object> map = new HashMap<String,Object>();

			map.put("rowBegin",(current-1)*pageSize);
			map.put("rowEnd",pageSize);
			map.put("planId",planId);
			map.put("sellingType",sellingType);
			map.put("startSellingTime",CommonUtil.getDateYYYYMMDDHH24MM());
			map.put("userId",userId);
			
			Map<String, Object> rtnMap = loanService.queryScatteredLoanInfo(map);
			
			String result = CommonUtil.setResultInfo(rtnMap, Consts.SUCCESS_CODE, Consts.SUCCESS_DESCRIBE);
			// 处理返回结果
			CommonUtil.responseJson(result, response);
			
		} catch (Exception e) {
			logger.error("获取散标列表数据发生异常:" + e.getMessage());
			String result = CommonUtil.setResultStringCn(
				new HashMap<String, Object>(),Consts.ERROR_CODE, "",e.getMessage());
			// 处理返回结果
			CommonUtil.responseJson(result, response);
			return;
		}finally{
			System.out.println("loan/getLoanListInfo接口\t执行耗时："+(System.currentTimeMillis()-a)/1000f+"秒");
			logger.debug("loan/getLoanListInfo接口\t执行耗时："+(System.currentTimeMillis()-a)/1000f+"秒");
		}
	}
	
	
	
//	/**
//	 * 散标列表(扩展条件:)
//	 * 
//	 * @param request
//	 * @return response
//	 * @throws Exception
//	 */
//	@RequestMapping(value = "/getLoanListInfo")
//	public void getRegularLoanList(HttpServletRequest request,
//			HttpServletResponse response) {
//		long a=System.currentTimeMillis();
//		Integer current = 1;
//		Integer pageSize = 10;//默认显示10条
//		
//		// 解密请求参数
//		Map<String, String> paramsMap = CommonUtil.decryptParamters(request);
//		String currentPageStr = paramsMap.get(Consts.Page.PAGE_CURRENT_NAME);//当前页
//		String pageSizeStr = paramsMap.get(Consts.Page.PAGE_SIZE_NAME);//页大小
//		String userId = paramsMap.get("userId");
//		String planId = paramsMap.get("planId");//页大小
//		String sellingType = paramsMap.get("sellingType");//上架类别
//		
//		try{
//			//分页参数
//			if (currentPageStr != null && !("".equals(currentPageStr))) {
//				current = Integer.parseInt(currentPageStr);
//			}
//			if (pageSizeStr != null && !("".equals(pageSizeStr))) {
//				pageSize = Integer.parseInt(pageSizeStr);
//			}
//			
//			Map<String,Object> map = new HashMap<String,Object>();
//
//			map.put("rowBegin",(current-1)*pageSize);
//			map.put("rowEnd",pageSize);
//			map.put("planId",planId);
//			map.put("sellingType",sellingType);
//			map.put("startSellingTime",CommonUtil.getDateYYYYMMDDHH24MM());
//			//获取上架产品总数
//			int totalNum = loanService.queryScatteredLoanInfoCount(map);
//			
//			List<Scattered> scatteredList = loanService.queryScatteredLoanInfo(map);
//			/**
//			 * 剩余金额小于起头金额，返回100%
//			 * 当产品已经超过下架时间，返回100%
//			 */
//			List<Map<String,Object>> resultListMap = new ArrayList<Map<String,Object>>();
//			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//			
//			Map<String, Object> map2 = new HashMap<String, Object>();
//			String investUserNum = "";
//			
//			StringBuffer loadIdBf=new StringBuffer();
//			for(int i =0;i<scatteredList.size();i++){
//				loadIdBf.append(String.valueOf(scatteredList.get(i).getId())+",");
//			}
//			String loadId=loadIdBf.toString();
//			Map<String,Object> listEx=null;
//			
//			if(loadId.lastIndexOf(",")!=-1){
//				loadId=loadId.substring(0,loadId.lastIndexOf(","));
//				logger.debug("queryOrderByIdPeopleNumEx传值参数-------"+loadId);
//				map2.put("loanId", loadId);
//				listEx=loanService.queryOrderByIdPeopleNumEx(map2);
//				logger.debug("queryOrderByIdPeopleNumEx返回结果-------"+listEx);
//			}
//			
//			//获取用户渠道等级积分数据
//			UserChannelPoint userChannelPoint = null;
//			if (StringUtils.isNotBlank(userId)) {
//				Map<String,Object> parm = new HashMap<String, Object>();
//				parm.put("userId", userId);
//				userChannelPoint = userChannelPointService.findChannelPointByParm(parm);
//			}
//
//			for(int i =0;i<scatteredList.size();i++){
//				Scattered sc = scatteredList.get(i);
//				Map<String,Object> scMap = new HashMap<String,Object>();
//				scMap.put("scatteredLoanId", sc.getId());//id
//				scMap.put("productName", sc.getProductName());//
//				scMap.put("borrowType", sc.getBorrowType());
//				scMap.put("annualRate", sc.getAnnualRate());
//				scMap.put("remanPeriods", sc.getRemanPeriods()); //剩余期数
//				scMap.put("contactAmount", sc.getContactAmount());
////				scMap.put("finishedRatio", DecimalFormatUtil.getDecimalFormat0(sc.getFinishedRatio()));
////				scMap.put("finishedRatio", sc.getFinishedRatio());
//				scMap.put("finishedRatio", DecimalFormatUtil.getDecimalFormat0(BigDecimal.ONE.compareTo(sc.getFinishedRatio())>0 && BigDecimal.ZERO.compareTo(sc.getFinishedRatio())<0?BigDecimal.ONE:sc.getFinishedRatio()));
//				scMap.put("remanAmount", sc.getRemanAmount());
//				scMap.put("perServingAmount", sc.getPerServingAmount());
//				scMap.put("investMinAmount", sc.getInvestMinAmount());
//				scMap.put("openSelling", sc.getOpenSelling());
//				scMap.put("loanId", sc.getBidId());
//				scMap.put("planId", sc.getPlanId());
//				scMap.put("isAdjustRate", sc.getIsAdjustRate());
//				scMap.put("remanDays", sc.getRemanDays());	//剩余天数（替换剩余期数）			
//				BigDecimal adjustRate = BigDecimal.ZERO; 
//				if ("Y".equals(sc.getIsAdjustRate())) {
//					if (userChannelPoint != null) {
//						adjustRate = sc.getMaxAdjustRate().multiply(
//								new BigDecimal(userChannelPoint.getFixFloatRateChannel()));
//					}
//				}
//				//调整利率
//				scMap.put("adjustRate", adjustRate.setScale(1, RoundingMode.DOWN));
//
//				// 获取标的列表人数
//				if(listEx!=null&&listEx.size()!=0&&listEx.size()==scatteredList.size()){
//					if(listEx.containsKey(String.valueOf(sc.getId()))){
//						scMap.put("investUserNum", listEx.get(String.valueOf(sc.getId())));
//					}else{
//						scMap.put("investUserNum", "1");
//					}
//				}else{
//					map2.put("loanId", sc.getId());
//					investUserNum = loanService.queryOrderByIdPeopleNum(map2);
//					scMap.put("investUserNum", investUserNum);
//				}
//				resultListMap.add(scMap);
//			}
//			
//			Map<String, Object> mapResult = new HashMap<String, Object>();
//			mapResult.put("totalNum", totalNum);
//			mapResult.put("listSize", String.valueOf(resultListMap.size()));
//			mapResult.put("list", resultListMap);
//			
//			mapResult.put("resmsg_cn", "");
//			String result = CommonUtil.setResultInfo(mapResult, Consts.SUCCESS_CODE, Consts.SUCCESS_DESCRIBE);
//			// 处理返回结果
//			CommonUtil.responseJson(result, response);
//			
//		} catch (Exception e) {
//			logger.error("获取散标列表数据发生异常:" + e.getMessage());
//			String result = CommonUtil.setResultStringCn(
//				new HashMap<String, Object>(),Consts.ERROR_CODE, "",e.getMessage());
//			// 处理返回结果
//			CommonUtil.responseJson(result, response);
//			return;
//		}finally{
//			System.out.println("loan/getLoanList接口\t执行耗时："+(System.currentTimeMillis()-a)/1000f+"秒");
//			logger.debug("loan/getLoanList接口\t执行耗时："+(System.currentTimeMillis()-a)/1000f+"秒");
//		}
//	}

	/**
	 * 根据Id获取标的详情信息
	 * 
	 * @param request
	 * @return response
	 * @throws Exception
	 */
	@RequestMapping(value = "/getLoanDetailById")
	public void getLoanDetailById(HttpServletRequest request,
			HttpServletResponse response) {

		// 解密请求参数
		Map<String, String> paramsMap = CommonUtil.decryptParamters(request);
		String loanId = paramsMap.get("scatteredLoanId");// 标的id

		try {
			// 参数检查
			if(StringUtils.isBlank(loanId)){
				String result = CommonUtil.setResultStringCn(
						new HashMap<String, Object>(), Consts.ERROR_CODE,
						"", Message.CnDescriptionExpression.BUSINESSE_ERROR);
				CommonUtil.responseJson(result, response);
				return;
			}
			
			// 获取标的列表信息
			HashMap<String,Object> map = new HashMap<String,Object>();
			map.put("loanId",loanId);
			
			Scattered scattered = loanService.queryScatteredByLoanId(map);
			JSONObject json = new JSONObject();
			json.put("rescode", Consts.SUCCESS_CODE);
			json.put("resmsg_cn", "");
			if (scattered != null) {
				json.put("loanDetail", scattered);
			} else {
				json.put("rescode", Consts.CHECK_CODE);
				json.put("resmsg_cn", "获取标的信息失败");
			}
			
			// 处理返回结果
			CommonUtil.responseJson(json.toString(), response);
		} catch (Exception e) {
			logger.error("loan/getLoanDetailInfo 异常:" + e.getMessage());
			String result = CommonUtil.setResultStringCn(
				new HashMap<String, Object>(),Consts.ERROR_CODE, "",e.getMessage());
			// 处理返回结果
			CommonUtil.responseJson(result, response);
			return;
		}
	}
	
	
	/**
	 * 获取标的借款详细信息
	 * 
	 * @param request
	 * @return response
	 * @throws Exception
	 */
	@RequestMapping(value = "/getLoanDetailInfo")
	public void getLoanDetailInfo(HttpServletRequest request,
			HttpServletResponse response) {

		// 解密请求参数
		Map<String, String> paramsMap = CommonUtil.decryptParamters(request);
		String loanId = paramsMap.get("scatteredLoanId");// 标的id

		try {
			// 参数检查
			Map<String, String> checkRes = getLoanDetailCheck(paramsMap);
			if (!Consts.SUCCESS_CODE.equals(checkRes.get("code"))) {
				logger.error("获取标的详细信息数据检查失败:" + checkRes.get("message"));
				String result = CommonUtil.setResultStringCn(
						new HashMap<String, Object>(), checkRes.get("code"),
						"", checkRes.get("message"));
				CommonUtil.responseJson(result, response);
				return;
			}
			
			// 获取标的列表信息
			HashMap<String,Object> map = new HashMap<String,Object>();
			map.put("scatteredLoanId",loanId);
			
			String result = loanService.getLoanDetail(map);
			
			// 处理返回结果
			CommonUtil.responseJson(result, response);
		} catch (Exception e) {
			logger.error("loan/getLoanDetailInfo 异常:" + e.getMessage());
			String result = CommonUtil.setResultStringCn(
				new HashMap<String, Object>(),Consts.ERROR_CODE, "",e.getMessage());
			// 处理返回结果
			CommonUtil.responseJson(result, response);
			return;
		}
	}
	
	private Map<String,String> getUserListByLoanIdCheck(Map<String,String> map){
		Map<String,String> resultMap = new HashMap<String,String>();
//		String loanId = map.get("scatteredLoanId");// 标的id
		String loanId = map.get("loanId");// 标的id
		
		if(StringUtils.isBlank(loanId)){
			resultMap.put("code", Consts.ERROR_CODE);
			resultMap.put("message","标的id为空!");
			return resultMap;
		}
		
		resultMap.put("code", Consts.SUCCESS_CODE);
		resultMap.put("message", Consts.SUCCESS_DESCRIBE);
		
		return resultMap;
	}
	
	private Map<String,String> getUserListByLoanIdWxCheck(Map<String,String> map){
		Map<String,String> resultMap = new HashMap<String,String>();
//		String loanId = map.get("scatteredLoanId");// 标的id
		String loanId = map.get("scatteredLoanId");// 标的id
		
		if(StringUtils.isBlank(loanId)){
			resultMap.put("code", Consts.ERROR_CODE);
			resultMap.put("message",
					Message.CnDescriptionExpression.BUSINESSE_ERROR);
			return resultMap;
		}
		
		resultMap.put("code", Consts.SUCCESS_CODE);
		resultMap.put("message", Consts.SUCCESS_DESCRIBE);
		
		return resultMap;
	}
	
	/**
	 * 获取标的相关资料(图片)
	 * 
	 * @param request
	 * @return response
	 * @throws Exception
	 */
	@RequestMapping(value = "/getLoanMaterial")
	public void getLoanMaterial(HttpServletRequest request,
			HttpServletResponse response) {

		// 解密请求参数
		Map<String, String> paramsMap = CommonUtil.decryptParamters(request);
		String loanId = paramsMap.get("loanId");// 标的id

		try {
			// 参数检查
			Map<String, String> checkRes = getLoanMaterialCheck(paramsMap);
			if (!Consts.SUCCESS_CODE.equals(checkRes.get("code"))) {
				logger.error("获取标的图片信息数据检查失败:" + checkRes.get("message"));
				String result = CommonUtil.setResultStringCn(
						new HashMap<String, Object>(), checkRes.get("code"),
						"", checkRes.get("message"));
				CommonUtil.responseJson(result, response);
				return;
			}
			
			HashMap<String,Object> map = new HashMap<String,Object>();
			map.put("loanId",loanId);
			
			String result = loanService.getLenderMaterial(map);
			
			// 处理返回结果
			CommonUtil.responseJson(result, response);
		} catch (Exception e) {
			logger.error("loan/getLoanMaterial 异常:" + e.getMessage());
			String result = CommonUtil.setResultStringCn(
				new HashMap<String, Object>(),Consts.ERROR_CODE, "",e.getMessage());
			// 处理返回结果
			CommonUtil.responseJson(result, response);
			return;
		}
	}
	
	private Map<String,String> getLoanMaterialCheck(Map<String,String> map){
		Map<String,String> resultMap = new HashMap<String,String>();
		String loanId = map.get("loanId");// 标的id
		
		if(StringUtils.isBlank(loanId)){
			resultMap.put("code", Consts.ERROR_CODE);
			resultMap.put("message",
					Message.CnDescriptionExpression.BUSINESSE_ERROR);
			return resultMap;
		}
		
		resultMap.put("code", Consts.SUCCESS_CODE);
		resultMap.put("message", Consts.SUCCESS_DESCRIBE);
		
		return resultMap;
	}
	
	
	
	
	/**
	 * 当天投资人列表(活期)
	 * 
	 * @param request
	 * @return response
	 * @throws Exception
	 */
	@RequestMapping(value = "/currentInvestList")
	public void currentInvestList(HttpServletRequest request,
			HttpServletResponse response) {
		// 解密请求参数
		Map<String, String> paramsMap = CommonUtil.decryptParamters(request);
		
		String currentPageStr = paramsMap.get(Consts.Page.PAGE_CURRENT_NAME);//当前页
		String pageSizeStr = paramsMap.get(Consts.Page.PAGE_SIZE_NAME);//页大小
		Integer current = 1;
		Integer pageSize = 10;//默认显示10条
//		String loanId = paramsMap.get("loanId");// 标的id(key)
		
		try {
			// 参数检查
//			Map<String, String> checkRes = getUserListByLoanIdCheck(paramsMap);
//			if (!Consts.SUCCESS_CODE.equals(checkRes.get("code"))) {
//				logger.error("获取投资人列表(活期)数据检查失败:" + checkRes.get("message"));
//				String result = CommonUtil.setResultStringCn(
//						new HashMap<String, Object>(), checkRes.get("code"),
//						"", checkRes.get("message"));
//				CommonUtil.responseJson(result, response);
//				return;
//			}
			
			//分页参数
			if (currentPageStr != null && !("".equals(currentPageStr))) {
				current = Integer.parseInt(currentPageStr);
			}
			if (pageSizeStr != null && !("".equals(pageSizeStr))) {
				pageSize = Integer.parseInt(pageSizeStr);
			}
			
			// 获取标的列表信息
			HashMap<String,Object> map = new HashMap<String,Object>();
//			map.put("loanId",loanId);
			map.put("currentPage", current);
			map.put("pageSize", pageSize);
			String result = loanService.currentInvestList(map);
			
			// 处理返回结果
			CommonUtil.responseJson(result, response);
		} catch (Exception e) {
			logger.error("loan/currentInvestList 异常:" + e.getMessage());
			String result = CommonUtil.setResultStringCn(
				new HashMap<String, Object>(),Consts.ERROR_CODE, "",e.getMessage());
			// 处理返回结果
			CommonUtil.responseJson(result, response);
			return;
		}
	}
	
	
	/**
	 * 当天投资人数(活期)
	 * 
	 * @param request
	 * @return response
	 * @throws Exception
	 */
	@RequestMapping(value = "/currentInvestNum")
	public void currentInvestNum(HttpServletRequest request,
			HttpServletResponse response) {
		// 解密请求参数
		Map<String, String> paramsMap = CommonUtil.decryptParamters(request);
		//获取标的id
//		String loanId = paramsMap.get("loanId");// 标的id(key)
		try {
			// 参数检查
//			Map<String, String> checkRes = getUserListByLoanIdCheck(paramsMap);
//			if (!Consts.SUCCESS_CODE.equals(checkRes.get("code"))) {
//				logger.error("获取投资人列表(活期)数据检查失败:" + checkRes.get("message"));
//				String result = CommonUtil.setResultStringCn(
//						new HashMap<String, Object>(), checkRes.get("code"),
//						"", checkRes.get("message"));
//				CommonUtil.responseJson(result, response);
//				return;
//			}
			
			// 获取活期当天购买人数
			HashMap<String,Object> map = new HashMap<String,Object>();
//			map.put("loanId",loanId);
			
			String result= loanService.currentInvestNum(map);
			// 处理返回结果
			CommonUtil.responseJson(result, response);
		} catch (Exception e) {
			logger.error("loan/currentInvestNum 异常:" + e.getMessage());
			String result = CommonUtil.setResultStringCn(
				new HashMap<String, Object>(),Consts.ERROR_CODE, "",e.getMessage());
			// 处理返回结果
			CommonUtil.responseJson(result, response);
			return;
		}
	}
}
